from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Optional

mcp = FastMCP("Geoclue2 MCP Server")

"""
面向 geoclue2 软件的 MCP Server

MCP tools 列表：
1. geoclue_service_control - 控制 geoclue 服务的启动、停止、重启和重载
   参数：action (str) - 服务操作类型：start|stop|restart|reload
   返回：统一的 JSON 结构，包含命令执行结果
"""

@mcp.tool()
def geoclue_service_control(action: str) -> dict:
    """
    控制 geoclue 服务的状态
    
    参数:
        action: 服务操作类型，可选值：start（启动）、stop（停止）、restart（重启）、reload（重载）
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 实际执行的命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    valid_actions = ["start", "stop", "restart", "reload"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} geoclue.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Valid actions are: {', '.join(valid_actions)}"
        }
    
    command = ["systemctl", action, "geoclue.service"]
    
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command execution timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()